part of '../index.dart';

class MessageGiftSvga extends StatefulWidget {
  const MessageGiftSvga(this.url, {super.key, this.callback});
  final String url;
  final VoidCallback? callback;

  @override
  State<MessageGiftSvga> createState() => _MessageGiftSvgaState();
}

class _MessageGiftSvgaState extends State<MessageGiftSvga>
    with SingleTickerProviderStateMixin {
  late final SVGAAnimationController _controller;
  bool _callbackExecuted = false;

  @override
  void initState() {
    _controller = SVGAAnimationController(vsync: this);
    _loadAnimation();
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _loadAnimation() async {
    final videoItem = await SVGAParser.shared.decodeFromURL(widget.url);
    if (!mounted) return;

    _controller.videoItem = videoItem;
    _controller.forward().whenComplete(() {
      if (mounted) {
        _controller.videoItem = null;
      }
    });

    _controller.addListener(() {
      if (_controller.isCompleted && !_callbackExecuted && mounted) {
        _callbackExecuted = true;
        _controller.stop();
        widget.callback?.call();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SVGAImage(_controller);
  }
}
